import { login, getUserInfo, getUserDetailById } from '@/api/user'
import { getToken, setToken, removeToken, setTime } from '@/utils/auth'
export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {}
  },
  mutations: {
    // 设置token
    setToken(state, data) {
      state.token = data
      setToken(data)
      setTime()
    },
    // 删除token
    removeToken(state) {
      state.token = null
      removeToken()
    },
    // 设置用户资料
    getUserInfo(state, data) {
      state.userInfo = data
    },
    // 删除用户资料
    removeUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 登录的action
    async login(context, data) {
      // data是表单数据
      // await 只会返回Promise的成功状态的结果
      const res = await login(data)
      context.commit('setToken', res)
    },
    // 获取用户资料
    async getUserInfo(context) {
      const res = await getUserInfo()
      const res2 = await getUserDetailById(res.userId)
      console.log(res)
      context.commit('getUserInfo', { ...res, ...res2 })
      return res
    },
    logout(context) {
      context.commit('removeToken')
      context.commit('removeUserInfo')
    }
  }
}
